package main

import (
	"flag"
	"github.com/go-kratos/kratos-layout/internal/biz"
	"github.com/go-kratos/kratos-layout/internal/conf"
	"github.com/go-kratos/kratos/v2/config"
	"os"

	"github.com/go-kratos/kratos/v2"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/tracing"
	"github.com/go-kratos/kratos/v2/transport/grpc"
	"github.com/go-kratos/kratos/v2/transport/http"

	_ "go.uber.org/automaxprocs"
)

// go build -ldflags "-X main.Version=x.y.z"
var (
	// Name is the name of the compiled software.
	Name string
	// Version is the version of the compiled software. use eureka kratos auto set eureka.metadata["Version"] = service.Version
	Version string
	// flagconf is the config flag.
	flagconf string

	id, _ = os.Hostname()
)

const appConfigKey = "application"

func init() {
	flag.StringVar(&Name, "name", "helloworld", "name of the application, eg: -name myapp")
	flag.StringVar(&flagconf, "conf", "../../configs", "config path, eg: -conf config.yaml")
}

func newApp(logger log.Logger, gs *grpc.Server, hs *http.Server, rs registrySet, up biz.CleanUp) *kratos.App {
	var opts = []kratos.Option{
		kratos.ID(id),
		kratos.Name(Name),
		kratos.Version(Version),
		kratos.Metadata(map[string]string{}),
		kratos.Logger(logger),
		kratos.BeforeStop(up.BeforeStop),
		kratos.AfterStop(up.AfterStop),
		kratos.Server(
			gs,
			hs,
		),
	}

	for _, v := range rs {
		opts = append(opts, kratos.Registrar(v))
	}

	return kratos.New(opts...)
}

func main() {
	flag.Parse()
	logger := log.With(log.NewStdLogger(os.Stdout),
		"ts", log.DefaultTimestamp,
		"caller", log.DefaultCaller,
		"service.id", id,
		"service.name", Name,
		"service.version", Version,
		"trace.id", tracing.TraceID(),
		"span.id", tracing.SpanID(),
	)

	//set global logger when you use log. Info(), you can also print the time or code line number
	log.SetLogger(logger)

	c := LoadConfigSequentially()
	defer c.Close()

	var bc conf.Bootstrap
	if err := c.Scan(&bc); err != nil {
		panic(err)
	}

	//update config when configuration center change
	c.Watch(appConfigKey, func(key string, value config.Value) {
		err := c.Scan(&bc)
		if err != nil {
			log.Error(err)
		}
	})

	app, cleanup, err := wireApp(&bc, bc.Application.Server, bc.Application.Data, logger)
	if err != nil {
		panic(err)
	}
	defer cleanup()

	initTracer(app, bc.Application.Tracing)

	// start and wait for stop signal
	if err := app.Run(); err != nil {
		panic(err)
	}
}
